package com.itsu.job.rpc.request;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.itsu.job.config.Job;
import com.itsu.job.config.JobProperties;
import com.itsu.job.context.JobHelper;
import com.itsu.job.rpc.model.JobResp;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jerry.Su
 * @Date 2022/1/28 14:22
 */
@Slf4j
public class ListJobRequestHandler extends JobRpcRequestHandler {

    final JobProperties jobProperties;

    public ListJobRequestHandler(JobProperties jobProperties) {
        this.jobProperties = jobProperties;
    }

    @Override
    public Map<String, Object> apply(String uri, String requestData) {
        MapBuilder<String, Object> builder = MapUtil.builder();
        try {
            List<Job> jobs = jobProperties.getJobs();
            List<JobResp> jobList = jobs.stream().map(job -> {
                JobResp jobResp = new JobResp();
                BeanUtil.copyProperties(job, jobResp);
                try {
                    jobResp.setRegisterHost(InetAddress.getLocalHost().getHostAddress());
                } catch (UnknownHostException e) {
                    log.error("unknown host exception happened");
                    jobResp.setRegisterHost("unknown");
                }
                jobResp.setStatus(JobHelper.scheduleFuture.containsKey(job.getJobId()) ? 1 : 0);
                return jobResp;
            }).collect(Collectors.toList());
            builder.put("code", 0);
            builder.put("data", jobList);
        } catch (Exception e) {
            log.error("list job error", e);
            builder.put("code", -1);
            builder.put("msg", e.getMessage());
        }
        return builder.build();
    }


}
